import {Component, ElementRef, OnInit, Renderer2, ViewChild} from '@angular/core';
import {NzContextMenuService, NzMessageService, NzModalService} from 'ng-zorro-antd';
import {AppService} from '../../../app.service';
import {XcUploadTool} from '../../../common/xc-upload.tool';
import {FileManagementService} from '../file-management.service';
import {CommonTool} from '../../../common/common.tool';
import {environment} from '../../../../environments/environment';
import {MusicPlayerComponent} from '../../../common/music-player/music-player.component';
import {TableFindModel} from '../../../common/table-find/table-find.model';
import {LoginDto, SystemDto} from '../../../base/base.model';
import {ActivatedRoute, Router} from '@angular/router';
import Viewer from 'viewerjs';

@Component({
  selector: 'app-file-management',
  templateUrl: './file.component.html',
  styleUrls: ['./file.component.scss']
})
export class FileComponent implements OnInit {

  @ViewChild(MusicPlayerComponent, {static: true})
  public musicPlayerComponent: MusicPlayerComponent;
  public commonTool = CommonTool;
  public recommendMovie: Array<{ name, value }> = [];
  public tableFindModel: TableFindModel;
  public tableFindModel1: TableFindModel;
  public tableFindModel2: TableFindModel;
  public folderId; // 当前目录
  public parentId;
  public edit = {isFile: true, name: '', id: '', isVisible: false, okDisabled: false, nameStatus: ''};
  public createFolder = {
    name: '',
    isVisible: false,
    okDisabled: true,
    nameStatus: ''
  };
  public createCdn = {
    fileId: '',
    fixed: '',
    isVisible: false
  };
  public selectFolder = {isVisible: false, isCopy: true, okText: ''};
  public share = {
    isVisible: false,
    fileIds: [],
    folderIds: [],
    okDisabled: false,
    needCode: '0',
    validTime: '0',
    remark: ''
  };
  public shareUrl = {
    url: '',
    isVisible: false,
    drawCode: ''
  };
  public showMusicPlay = false;
  public pictureFiles: Array<any>;
  public showPicture = false;
  public videoPlay = {url: '', isVisible: false};
  public upload = {isVisible: false};
  public package = {
    isVisible: false,
    nameStatus: '',
    fileIds: [],
    folderIds: [],
    okDisabled: true,
    name: ''
  };
  public renewalSize = 10485760; // 文件读取大小
  public count; // 计数
  public viewer;
  public imgConfig = {};
  public system: SystemDto;
  public cdn = {isVisible: false, url: ''};

  public compressUrl = '?open=0&w=30&h=30';
  public compressUrl1 = '?open=0';
  public compressUrl2 = '?open=0&w=30&h=50';

  private xcUploadTool = new XcUploadTool();

  constructor(private nzContextMenuService: NzContextMenuService,
              public fileManagementService: FileManagementService,
              private modalService: NzModalService,
              public appService: AppService,
              public router: Router,
              public activateRoute: ActivatedRoute,
              private message: NzMessageService,
              public renderer: Renderer2,
              public elementRef: ElementRef) {
    // 获取系统信息
    this.system = new SystemDto(JSON.parse(sessionStorage.getItem(environment.systemKey)));
    for (const systemInfo of this.system.systemInfos) {
      this.imgConfig[systemInfo.code] = systemInfo.value;
    }
    for (const systemInfo of this.system.systemInfos) {
      if (systemInfo.code === 'recommend_movie') {
        this.recommendMovie.push({name: systemInfo['name'], value: systemInfo.value});
      }
    }
    this.count = 0;
    this.tableFindModel = new TableFindModel();
    this.tableFindModel1 = new TableFindModel();
    this.tableFindModel2 = new TableFindModel();
    this.folderId = this.activateRoute.snapshot.queryParams['folderId'];
    if (!this.folderId) {
      this.folderId = 'root';
    }
    this.pictureFiles = [];
    this.init();
    this.uploadInit();
  }

  // 初始化
  ngOnInit(): void {
    const that = this;
    if (window.history && window.history.pushState) {
      window.onpopstate = (e) => {
        const folderId = that.activateRoute.snapshot.queryParams['folderId'];
        if (folderId && folderId !== 'root') {
          const data = CommonTool.getUrlParam(e['target']['location'].href);
          if (data['folderId']) {
            that.folderId = data['folderId'];
          } else {
            that.folderId = 'root';
          }
          that.tableFindModel.getData(null, null);
        }
      };
    }
    // 拖动文件上传
    this.renderer.listen('window', 'dragover', (event) => {
      // 取消默认浏览器拖拽效果
      event.preventDefault();
    });
    const drop = this.elementRef.nativeElement.querySelector('#upload-file');
    this.renderer.listen(drop, 'drop', (e) => {
      const dataTransfer = e.dataTransfer;
      if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
        e.preventDefault();
        that.xcUploadTool.handleFileDirectory(dataTransfer).then((files) => {
          that.uploadFolderFile(files, that.folderId);
        });
      }
    });
  }

  /**
   * 初始化
   */
  public init() {
    const myThis = this;
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const disabledFun = (formInfo, that) => {
      let bool = true;
      that.dataModels.forEach(dataModel => {
        if (dataModel.selected) {
          bool = false;
        }
      });
      return bool;
    };
    const config = {
      finds: [
        {name: '文件名', field: 'name', type: COMMON_TYPE.find.INPUT}
      ],
      buttons: [
        {
          name: '创建目录', type: COMMON_TYPE.button.BUTTON, confirmFun: () => {
            myThis.createFolder.isVisible = true;
          }
        },
        {
          name: '上传文件', type: COMMON_TYPE.button.BUTTON, confirmFun: () => {
            myThis.selectFile();
          }
        },
        {
          name: '上传文件夹', type: COMMON_TYPE.button.BUTTON, confirmFun: () => {
            myThis.uploadFolder();
          }
        },
        {
          name: '音乐播放器', type: COMMON_TYPE.button.BUTTON,
          confirmFun: (formInfo, that) => {
            myThis.showMusicPlay = true;
            myThis.handleMp3(null);
          }
        },
        {
          name: '分享', type: COMMON_TYPE.button.BUTTON, disabledFun, confirmFun: (formInfo, that) => {
            const selectedArray = that.getSelectedArray();
            const fileIds = [];
            const folderIds = [];
            selectedArray.forEach(dataModel => {
              if (dataModel.isFile) {
                fileIds.push(dataModel.data.id);
              } else {
                folderIds.push(dataModel.data.id);
              }
            });
            myThis.share.isVisible = true;
            myThis.share.fileIds = fileIds;
            myThis.share.folderIds = folderIds;
          }
        },
        {
          name: '复制', type: COMMON_TYPE.button.BUTTON, disabledFun, confirmFun: (formInfo, that) => {
            myThis.selectFolder = {isVisible: true, isCopy: true, okText: '复制'};
            myThis.init1();
          }
        },
        {
          name: '移动', type: COMMON_TYPE.button.BUTTON, disabledFun, confirmFun: (formInfo, that) => {
            myThis.selectFolder = {isVisible: true, isCopy: false, okText: '移动'};
            myThis.init1();
          }
        },
        {
          name: '打包', type: COMMON_TYPE.button.BUTTON, disabledFun, confirmFun: (formInfo, that) => {
            const selectedArray = that.getSelectedArray();
            const fileIds = [];
            const folderIds = [];
            selectedArray.forEach(dataModel => {
              if (dataModel.isFile) {
                fileIds.push(dataModel.data.id);
              } else {
                folderIds.push(dataModel.data.id);
              }
            });
            myThis.package.isVisible = true;
            myThis.package.fileIds = fileIds;
            myThis.package.folderIds = folderIds;
          }
        },
        {
          name: '删除', type: COMMON_TYPE.button.BUTTON, confirmFun(formInfo, that) {
            myThis.delete(myThis.tableFindModel.getSelectedArray());
          }
        },
        {name: '搜索', type: COMMON_TYPE.button.SEARCH}
      ],
      breadcrumb: {
        breadcrumbFun: (label) => {
          if (label['data'] != null) {
            myThis.folderId = label['data'].id;
          } else {
            myThis.folderId = 'root';
          }
          myThis.tableFindModel.getData(null, null);
        },
        labels: [] // 面包屑
      },
      tables: [
        {name: '', field: 'checkbox', type: COMMON_TYPE.table.CHECKBOX},
        {
          name: '', field: 'imageUrl', type: COMMON_TYPE.table.IMAGE,
          imageStyle: {cursor: 'pointer'},
          confirmFun: (dataModel) => {
            if (!dataModel['isFile']) {
              myThis.folderId = dataModel['data'].id;
              myThis.tableFindModel.getData(null, null);
            } else {
              myThis.showPicture = true;
              myThis.openFile(dataModel.data);
            }
          },
          initFun(dataModel, that) {// dataModel：初始化的数据，that:当前对象
            if (dataModel['isFile']) {
              // 获取后缀
              const suffix = CommonTool.getSuffix(dataModel.data.name);
              if (myThis.verifyImageSuffix(suffix)) {
                dataModel.data['imageUrl'] = dataModel.data['url'] + myThis.compressUrl;
                myThis.pictureFiles.push(dataModel.data);
              } else {
                const i = dataModel.data.name.lastIndexOf('.');
                const fileSuffix = dataModel.data.name.substring(i + 1, dataModel.data.name.length);
                if (myThis.imgConfig['disk_file_icon_' + fileSuffix]) {
                  dataModel.data['imageUrl'] = myThis.imgConfig['disk_file_icon_' + fileSuffix];
                } else {
                  dataModel.data['imageUrl'] = myThis.imgConfig['disk_icon_file'];
                }
              }
            }
          }
        },
        {
          name: '文件名',
          field: 'name',
          type: COMMON_TYPE.table.TITLE,
          isSort: true,
          titleStyle: {cursor: 'pointer'},
          confirmFun: (dataModel) => {
            if (!dataModel['isFile']) {
              myThis.folderId = dataModel['data'].id;
              myThis.tableFindModel.getData(null, null);
            } else {
              myThis.openFile(dataModel.data);
            }
          }
        },
        {name: '', field: 'createTime', type: COMMON_TYPE.table.DESCRIPTION},
        {
          name: '', field: 'size', type: COMMON_TYPE.table.DESCRIPTION,
          descriptionStyle: {cursor: 'pointer'},
          confirmFun: (dataModel) => {
            if (!dataModel['isFile']) {
              if (dataModel.data['size'] === '计算') {
                myThis.appService.setLoading(true);
                myThis.fileManagementService.getUserFolderSize(dataModel.data['id']).subscribe(res => {
                  dataModel.data['size'] = CommonTool.getSpace(res.size);
                  myThis.appService.setLoading(false);
                });
              }
            }
          }
        },
        {
          name: '', field: '', type: COMMON_TYPE.table.OPERATE,
          initFun(dataModel, that) {// data：初始化的数据，that:全局this
            if (!dataModel['isFile']) {
              dataModel['cdn'] = false;
              dataModel['download'] = false;
            }
          },
          operates: [
            {
              name: '下载', field: 'download', confirmFun(dataModel, that) {
                location.href = dataModel.data['url'];
              }
            },
            {
              name: '编辑', field: 'edit', confirmFun(dataModel, that) {
                myThis.edit = {
                  id: dataModel.data.id,
                  name: dataModel.data.name,
                  isVisible: true,
                  okDisabled: false,
                  nameStatus: '',
                  isFile: dataModel['isFile']
                };
              }
            },
            {
              name: 'cdn', field: 'cdn', confirmFun(dataModel, that) {
                if (dataModel.data.fixed) {
                  myThis.createCdn.fixed = dataModel.data.fixed;
                } else {
                  myThis.createCdn.fixed = dataModel.data.id;
                }
                myThis.createCdn.fileId = dataModel.data.id;
                myThis.createCdn.isVisible = true;
              }
            },
            {
              name: '删除', field: 'delete', confirmFun(dataModel, that) {
                myThis.delete([dataModel]);
              }
            }
          ]
        }
      ],
      initDataFun(formInfo, sortPage, callback, that) {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        myThis.initData(formInfo, sortPage, callback, myThis.folderId);
      },
      openPaging: false,
      frontSort: false
    };
    this.tableFindModel.initConfig(config);
  }

  /**
   * 打开文件
   */
  public openFile(data) {
    const suffix = CommonTool.getSuffix(data.name);
    if (suffix === '.mp3') {
      this.handleMp3(data.id);
    } else if (data['url']) {
      this.handleFile(data);
    } else {
      this.handleFile(data);
    }
  }

  /**
   * 处理mp3
   */
  public handleMp3(id) {
    this.musicPlayerComponent.setPlayList([]);
    this.tableFindModel.dataModels.forEach((ref) => {
      const suffix = CommonTool.getSuffix(ref.data['name']);
      if (suffix === '.mp3' && !ref.data['url']) {
        const playId = this.musicPlayerComponent.addMusic({
          name: ref.data['name'],
          url: ref.data['url']
        });
        if (id === ref.data['id']) {
          this.showMusicPlay = true;
          this.musicPlayerComponent.play(playId);
        }
      } else if (suffix === '.mp3') {
        const playId = this.musicPlayerComponent.addMusic({
          name: ref.data['name'],
          url: ref.data['url']
        });
        if (id === ref.data['id']) {
          this.showMusicPlay = true;
          this.musicPlayerComponent.play(playId);
        }
      }
    });
  }

  /**
   * 处理文件
   */
  public handleFile(data) {
    const that = this;
    const suffix = CommonTool.getSuffix(data.name);
    if (suffix === '.mp4') {
      this.videoPlay.isVisible = true;
      this.videoPlay.url = data['url'];
    } else if (this.verifyImageSuffix(suffix)) {
      if (!this.viewer) {
        this.viewer = new Viewer(document.getElementById('image'), {
          initialViewIndex: 0,
          url(image) {
            return image.src.split('?')[0] + that.compressUrl1;
          }
        });
      } else {
        this.viewer.update();
      }
      for (let i = 0; i < this.pictureFiles.length; i++) {
        if (data['id'] === this.pictureFiles[i]['id']) {
          this.viewer.view(i);
        }
      }
      this.viewer.show();
    }
  }

  /**
   * 验证后缀是否是图片
   * 图片名称 name
   */
  public verifyImageSuffix(suffix) {
    return suffix === '.jpg' || suffix === '.png' || suffix === '.jpeg' || suffix === 'gif' || suffix === 'bmp';
  }

  /**
   * 初始化数据
   */
  public initData(formInfo, sortPage, callback, folderId) {
    this.appService.setLoading(true);
    const req = {
      sortField: sortPage.sortField,
      sortRule: sortPage.sortRule,
      likeFields: ['name'],
      name: formInfo['name'],
      folderId
    };
    if (formInfo['name']) {
      req['folderId'] = null;
    } else if (!folderId) {
      req['folderId'] = 'root';
    }
    this.fileManagementService.getUserFolderFile(req).subscribe(res => {
      this.appService.setLoading(false);
      const array = [];
      this.pictureFiles = [];
      for (const arr of res['folders']) {
        arr.size = '计算';
        arr['imageUrl'] = this.imgConfig['disk_icon_folder'];
        array.push({data: arr, isFile: false});
      }
      for (const arr of res['files']) {
        arr.size = CommonTool.getSpace(arr.size);
        array.push({
          data: arr,
          isFile: true
        });
      }
      this.fileManagementService.getUserParentFolder(req['folderId']).subscribe(folders => {
        const labels = [{name: '全部', data: null}];
        for (const folder of folders.reverse()) {
          folder['imageUrl'] = this.imgConfig['disk_icon_folder'];
          labels.push({name: folder.name, data: folder});
        }
        this.tableFindModel.config.breadcrumb.labels = labels;
      });
      callback(array, {size: array.length});
      if (req['folderId'] !== 'root') {
        const url = CommonTool.analysisParam('/home/fileManage/file', {folderId: req['folderId']});
        this.router.navigateByUrl(url);
      } else {
        this.router.navigateByUrl('/home/fileManage/file');
      }
    });
  }

  /**
   * 初始化选择数据
   */
  public init1() {
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const myThis = this;
    const config1 = {
      finds: [
        {name: '文件夹名', field: 'name', type: COMMON_TYPE.find.INPUT}
      ],
      tables: [
        {
          name: '', field: 'imageUrl', type: COMMON_TYPE.table.IMAGE,
          imageStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        },
        {
          name: '文件夹名',
          field: 'name',
          type: COMMON_TYPE.table.TITLE,
          isSort: true,
          titleStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        }, {
          name: '', field: 'createTime', type: COMMON_TYPE.table.DESCRIPTION,
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        }
      ],
      buttons: [
        {name: '搜索', type: COMMON_TYPE.button.SEARCH}
      ],
      breadcrumb: {
        breadcrumbFun: (label) => {
          if (label['data'] != null) {
            myThis.parentId = label['data'].id;
          } else {
            myThis.parentId = 'root';
          }
          myThis.tableFindModel1.getData(null, null);
        },
        labels: [] // 面包屑
      },
      initDataFun(formInfo, sortPage, callback, that) {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        const req = {
          sortField: sortPage.sortField,
          sortRule: sortPage.sortRule,
          likeFields: ['name'],
          parentId: myThis.parentId,
          name: formInfo['name']
        };
        if (formInfo['name']) {
          req['parentId'] = null;
        } else if (!myThis.parentId) {
          req['parentId'] = 'root';
        }
        myThis.fileManagementService.getUserFolderList(req).subscribe(res => {
          const array = [];
          for (const arr of res) {
            arr['imageUrl'] = myThis.imgConfig['disk_icon_folder'];
            array.push({
              data: arr,
              isFile: false
            });
          }
          myThis.fileManagementService.getUserParentFolder(req['parentId']).subscribe(folders => {
            const labels = [{name: '全部', data: null}];
            for (const folder of folders.reverse()) {
              folder['imageUrl'] = myThis.imgConfig['disk_icon_folder'];
              labels.push({name: folder.name, data: folder});
            }
            myThis.tableFindModel1.config.breadcrumb.labels = labels;
          });
          callback(array, {size: array.length});
        });
      },
      openPaging: false,
      frontSort: false,
      openButton: false
    };
    this.tableFindModel1.initConfig(config1);
  }

  /**
   * 打包提交
   */
  public packageOk(folderId, pack) {
    this.appService.setLoading(true);
    this.fileManagementService.createUserFilePackage(folderId, {
      fileIds: pack.fileIds,
      folderIds: pack.folderIds,
      name: pack.name
    }).subscribe(res => {
      pack.name = '';
      pack.isVisible = false;
      this.tableFindModel.getData(null, null);
      this.message.success('打包成功！');
    });
  }

  /**
   * 移动文件及文件夹
   */
  public moveCopyFolderFile() {
    this.appService.setLoading(true);
    const selectedArray = this.tableFindModel.getSelectedArray();
    const fileIds = [];
    const folderIds = [];
    selectedArray.forEach(dataModel => {
      if (dataModel.isFile) {
        fileIds.push(dataModel.data.id);
      } else {
        folderIds.push(dataModel.data.id);
      }
    });
    if (!this.parentId) {
      this.parentId = 'root';
    }
    if (this.selectFolder.isCopy) {
      const data = {
        folderId: this.parentId
      };
      this.fileManagementService.createUserFolderFile(data, {fileIds, folderIds}).subscribe(res => {
        this.selectFolder.isVisible = false;
        this.parentId = null;
        this.tableFindModel.getData(null, null);
        this.message.success('复制成功！');
      });
    } else {
      this.fileManagementService.updateUserFolderFile(this.parentId, {fileIds, folderIds}).subscribe(res => {
        this.selectFolder.isVisible = false;
        this.parentId = null;
        this.tableFindModel.getData(null, null);
        this.message.success('移动成功！');
      });
    }
  }

  /**
   * 验证文件目录输入框
   * 参数 data 数据
   * 参数 field 字段
   */
  public folderInput(data, field) {
    if (!CommonTool.notNull(data[field])) {
      data[field + 'Status'] = 'error';
      data.okDisabled = true;
      return;
    }
    const pattern = new RegExp('[/\\\\:*?"<>|]');
    if (pattern.test(data[field])) {
      data[field + 'Status'] = 'error';
      data.okDisabled = true;
    } else {
      data.okDisabled = false;
      data[field + 'Status'] = '';
    }
  }

  /**
   * 修改文件名称
   */
  public updateFileFolder(edit) {
    this.appService.setLoading(true);
    if (edit.isFile) {
      this.fileManagementService.updateUserFile(edit.id, {name: edit.name}).subscribe(() => {
        edit.isVisible = false;
        this.tableFindModel.getData(null, null);
        this.message.success('修改成功！');
      });
    } else {
      this.fileManagementService.updateUserFolder(edit.id, {name: edit.name}).subscribe(() => {
        edit.isVisible = false;
        this.tableFindModel.getData(null, null);
        this.message.success('修改成功！');
      });
    }

  }

  /**
   * 共享文件关闭弹窗
   */
  public fileShareCancel() {
    this.share = {
      isVisible: false,
      fileIds: [],
      folderIds: [],
      okDisabled: false,
      needCode: '0',
      validTime: '0',
      remark: ''
    };
  }

  /**
   * 分享文件
   */
  public fileShare() {
    this.appService.setLoading(true);
    this.fileManagementService.createUserShare({
      fileIds: this.share.fileIds,
      folderIds: this.share.folderIds,
      needCode: this.share.needCode,
      validTime: this.share.validTime,
      remark: this.share.remark
    }).subscribe((res) => {
      this.shareUrl.url = location.origin + '/#/share/' + res.code;
      this.shareUrl.isVisible = true;
      this.shareUrl.drawCode = res.drawCode;
      this.fileShareCancel();
      this.appService.setLoading(false);
    });
  }

  /**
   * 确认创建弹窗
   */
  public createFolderOk(folderId) {
    this.appService.setLoading(true);
    const req = {
      name: this.createFolder.name
    };
    if (folderId !== 'root') {
      req['parentId'] = folderId;
    }
    this.fileManagementService.createFolder(req).subscribe(res => {
      this.createFolder.name = '';
      this.createFolder.isVisible = false;
      this.message.success('创建成功！');
      this.tableFindModel.getData(null, null);
    });
  }

  /**
   * 创建cdn确认回调
   */
  public createCdnOk(createCdn) {
    this.appService.setLoading(true);
    this.fileManagementService.createCdnUrl({fileId: createCdn.fileId, fixed: createCdn.fixed}).subscribe(res => {
      this.cdn.isVisible = true;
      this.createCdn.isVisible = false;
      this.cdn.url = res.cdnUrl;
      this.appService.setLoading(false);
    });
  }

  /**
   * 删除
   * 参数 data 数据
   */
  public delete(dataModels) {
    let index = 0;
    this.modalService.confirm({
      nzTitle: '确认要删除文件/目录吗?',
      nzContent: '<b style="color: red;">文件/目录删除后将无法找回哦！</b>',
      nzOkText: '确认',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.appService.setLoading(true);
        for (const dataModel of dataModels) {
          if (dataModel.isFile) {
            this.fileManagementService.deleteFile(dataModel.data.id).subscribe(res => {
              index++;
              if (index === dataModels.length) {
                this.message.success('删除成功！');
                this.tableFindModel.getData(null, null);
              }
            });
          } else {
            this.fileManagementService.deleteFolder(dataModel.data.id).subscribe(res => {
              index++;
              if (index === dataModels.length) {
                this.message.success('删除成功！');
                this.tableFindModel.getData(null, null);
              }
            });
          }
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 视频播放
   */
  public playMovie(url) {
    this.videoPlay.isVisible = true;
    this.videoPlay.url = url;
  }

  /**
   * 上传文件初始化
   */
  public uploadInit() {
    const myThis = this;
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const config = {
      tables: [
        {name: '名称', field: 'name', type: COMMON_TYPE.table.TEXT},
        {name: '大小', field: 'size', type: COMMON_TYPE.table.TEXT},
        {name: '进度', field: 'progress', type: COMMON_TYPE.table.PROGRESS},
        {
          name: '操作', field: '', type: COMMON_TYPE.table.OPERATE,
          initFun(dataModel, that) {// data：初始化的数据，that:全局this
            dataModel['cancel'] = true;
            dataModel['retry'] = false;
            if (dataModel['stopUpload']) {
              dataModel['start'] = true;
              dataModel['operateStop'] = false;
            } else {
              dataModel['start'] = false;
              dataModel['operateStop'] = true;
            }
          },
          operates: [
            {
              name: '暂停', field: 'operateStop', confirmFun(dataModel, table, that) {
                dataModel['start'] = true;
                dataModel['operateStop'] = false;
                myThis.xcUploadTool.stop(dataModel.id);
              }
            },
            {
              name: '开始', field: 'start', confirmFun(dataModel, table, that) {
                dataModel['start'] = false;
                dataModel['operateStop'] = true;
                myThis.xcUploadTool.start(dataModel.id);

              }
            },
            {
              name: '重试', field: 'retry', confirmFun(dataModel, table, that) {
                dataModel['operateStop'] = true;
                dataModel['retry'] = false;
                myThis.xcUploadTool.retry(dataModel.id);
              }
            },
            {
              name: '取消', field: 'cancel', confirmFun(dataModel, table, that) {
                if (dataModel['status'] === 'success') {
                  myThis.count--;
                }
                dataModel['stopUpload'] = true;
                that.dataModels.splice(dataModel.index, 1);
                const array = [];
                that.dataModels.forEach((data, index) => {
                  data.index = index;
                  array.push(data);
                });
                that.dataModels = array;
              }
            }
          ]
        }
      ],
      paging: {
        current: 1, // 默认显示第几页
        size: 5, // 默认每页多少条数据
        total: 0, // 总数
        limits: [] // 每页多少数据的可选参数
      },
      openPaging: true,
      frontSort: false,
      openFind: false
    };
    this.tableFindModel2.initConfig(config);
  }

  /**
   * 关闭上传
   */
  public cancelUpload() {
    this.tableFindModel.getData(null, null);
    for (const dataMode of  this.tableFindModel2.dataModels) {
      dataMode['stopUpload'] = true;
    }
    this.tableFindModel2.setDataModels([], {total: 0});
    this.upload.isVisible = false;
  }

  /**
   * 选择目录
   */
  public uploadFolder() {
    const $this = this;
    const input = document.createElement('input');
    input.style.display = 'none';
    input.setAttribute('multiple', '');
    input.setAttribute('webkitdirectory', '');
    input.type = 'file';
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
      $this.uploadFolderFile(e.target['files'], $this.folderId);
    };
  }

  /**
   * 选择文件
   */
  public selectFile() {
    const $this = this;
    const input = document.createElement('input');
    input.style.display = 'none';
    input.type = 'file';
    input.setAttribute('multiple', '');
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
      $this.uploadFolderFile(e.target['files'], $this.folderId);
    };
  }

  /**
   * 上传文件数据处理
   */
  public uploadFolderFile(files, folderId) {
    this.count = 0;
    this.upload.isVisible = true;
    const array = [];
    const dataArray = [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      let folderPath = '';
      if (file.webkitRelativePath !== '' && file.webkitRelativePath !== null && file.webkitRelativePath !== undefined) {
        const arrayPath = file.webkitRelativePath.split('/');
        arrayPath.pop();
        folderPath = arrayPath.join('/');
      }
      const data = {
        id: i,
        data: {
          file, // 文件
          index: 0,
          url: 0,
          fileIndex: 0,
          name: file.name,
          size: CommonTool.getSpace(file.size),
          progress: 0
        },
        stopUpload: false,
        reader: undefined,
        status: ''
      };
      array.push(data);
      dataArray.push({
        id: i,
        file, // 文件
        folderPath, // 目录路径
        resumed: true, // 开启断点续传
        folderId // 目录id
      });
    }
    this.tableFindModel2.initDataModels(array, {total: array.length});
    const tokenInfo = new LoginDto(JSON.parse(CommonTool.getCookie(environment.tokenKey)));
    const myThis = this;
    this.xcUploadTool.upload({
      appId: '', // AppId
      sign: '', // 签名信息
      token: tokenInfo.accessToken, // 用户token
      uploadType: 'token', // 上传类型，token上传/sign上传
      uploadUrl: this.fileManagementService.getUploadUrl(), // 上传的url地址
      isHttp: true,
      dataArray,
      loadingStart: (current, data, that) => {
        // 开始加载（计算md5）
        // current：当前进度
        // data：传入的数据对象
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        dataModel['isLoad'] = true;
        const COMMON_TYPE = TableFindModel.COMMON_TYPE;
        myThis.tableFindModel2.config.tables[2].type = COMMON_TYPE.table.TEXT;
        dataModel.data['progress'] = 0;
      },
      loadingProgress: (current, data, that) => {
        // 加载（计算md5）进度
        // current：当前进度
        // data：传入的数据对象
        // that: this对象
        // debugger;
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        const progress = parseInt((current / (data.file.size / 100)) + '');
        dataModel.data['progress'] = progress + '%';
      },
      loadingSuccess: (md5, current, data, that) => {
        // 加载（计算md5）完成
        // md5：计算出的md5
        // data：传入的数据对象
        // current：当前进度
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        dataModel.data['progress'] = '100%';
      },
      uploadStart: (current, data, that) => {
        // 开始上传
        // current：当前进度
        // data：传入的数据对象
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        dataModel['status'] = 'active';
        dataModel['isLoad'] = false;
        const COMMON_TYPE = TableFindModel.COMMON_TYPE;
        myThis.tableFindModel2.config.tables[2].type = COMMON_TYPE.table.PROGRESS;
      },
      uploadProgress: (current, data, that) => {
        // 上传进度
        // current：当前进度
        // data：传入的数据对象
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        dataModel['status'] = 'active';
        const progress = parseInt(Math.round(current / data.file.size * 100) + '');
        dataModel.data['progress'] = progress;
      },
      uploadSuccess: (current, data, res, that) => {
        // 上传完成
        // current：当前进度
        // data：传入的数据对象
        // res：请求返回对象
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        myThis.count++;
        dataModel['operateStop'] = false;
        dataModel['status'] = 'success';
        dataModel.data['progress'] = 100;
      },
      uploadFail: (data, res, that) => {
        // 上传失败
        // current：当前进度
        // data：传入的数据对象
        // res：请求返回对象
        // that: this对象
        const dataModel = myThis.tableFindModel2.dataModels[data.id];
        dataModel['status'] = 'exception';
        dataModel['retry'] = true;
        dataModel['operateStop'] = false;
      }
    });
  }

  /**
   * 复制
   */
  public copy(data) {
    const input = document.createElement('input');
    input.value = data;
    document.body.appendChild(input);
    input.select();
    if (document.execCommand('Copy')) {
      this.message.success('复制成功！');
    } else {
      this.message.success('复制失败！');
    }
    input.style.display = 'none';
  }
}
